package com.vf.s.mvc.biz.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.jfinal.aop.Inject;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.vf.core.controller.BaseController;
import com.vf.core.util.ExcelUtil;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.biz.BizKml;
import com.vf.s.common.model.biz.BizLayer;
import com.vf.s.common.model.biz.Point;
import com.vf.s.common.model.biz.BizProperty;
import com.vf.s.common.model.scene.Scene;
import com.vf.s.common.plugins.shiro.ShiroKit;
import com.vf.s.common.plugins.shiro.SimpleUser;
import com.vf.s.common.vector.kml.KmlLine;
import com.vf.s.common.vector.kml.KmlParser;
import com.vf.s.common.vector.kml.KmlPolygon;
import com.vf.s.common.vector.kml.KmlProperty;
import com.vf.s.mvc.biz.service.BizKmlService;

public class BizKmlController extends BaseController {
	
	private String rootPath = PathKit.getWebRootPath();
	
	@Inject
	private BizKmlService srv;
	
	public void index() {
		this.render("list.html");
	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String sqlExceptSelect = " FROM " + BizKml.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%' ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.CREATETIME  desc ";
		Page<BizKml> page = BizKml.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	public void delete() throws Exception {
		String id = getPara("id");
		BizKml model = BizKml.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				File file = new File(rootPath+model.getPath());
				if (file.exists()) {
					file.delete();
				}
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}

	ExecutorService executor = Executors.newFixedThreadPool(20);
	public void uploadForKml() {
		UploadFile uploadFile = getFile();
		try {
			String path = "/upload/kml/"+System.currentTimeMillis()+"/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			
			BizKml bizKml = new BizKml();
			bizKml.setId(UuidUtil.getUUID());
			bizKml.setName(uploadFile.getFileName());
			bizKml.setStatus("0");
			bizKml.setPath(path);
			String fileName=uploadFile.getFileName();
			if(uploadFile.getFile().renameTo(file) && bizKml.save()) {
				renderSuccess("导入成功，已启动异步入库进程！");
			    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
			        @Override
			        public Integer get() {
			            try {
			            	bizKml.setStatus("1");
			            	bizKml.setRemark("开始入库:"+DateKit.toStr(new Date(System.currentTimeMillis()),"yyyy-mm-dd hh:mm:ss" ));
			            	bizKml.update();
							KmlParser parser = new KmlParser();
							KmlProperty kmlProperty;
							File file = new File(rootPath+path);
							kmlProperty = parser.parseKmlForJAK(file);
							assert kmlProperty != null;
							if (kmlProperty.getKmlPoints().size() > 0) {
								for (int i=0;i<kmlProperty.getKmlPoints().size();i++) {
									srv.saveForBizPoint(fileName,kmlProperty.getKmlPoints().get(i),i);
								}
							}
							if (kmlProperty.getKmlLines().size() > 0) {
								for (KmlLine k : kmlProperty.getKmlLines()) {
									srv.saveForBizLine(fileName, k);
								}
							}
							if (kmlProperty.getKmlPolygons().size() > 0) {
								for (KmlPolygon k : kmlProperty.getKmlPolygons()) {
									srv.saveForKmlPolygon(fileName, k);
								}
							}
			            	bizKml.setStatus("2");
			            	bizKml.setRemark(bizKml.getRemark()+"--->入库完成:"+DateKit.toStr(new Date(System.currentTimeMillis()),"yyyy-mm-dd hh:mm:ss" ));
			            	bizKml.update();
			            } catch (Exception e) {
			                e.printStackTrace();
			                bizKml.setStatus("3");
			                bizKml.setRemark(e.getMessage());
			                bizKml.update();
			            }
			            return 3;
			        }
			    }, executor);
			    future.thenAccept(e -> System.out.println(e));
			}else {
				renderError("导入失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}
	
	public void uploadForCsv() {
		UploadFile uploadFile = getFile();
		try {
			String sceneId=this.getPara("sceneId");
			if(StrKit.isBlank(sceneId)) {
				renderError("必须指定场景！！！");
				return;
			}
			
			Scene bizScene=Scene.dao.findById(sceneId);
			if(bizScene==null) {
				renderError("场景已不存在！！！");
				return;
			}
			
			SimpleUser simpleUser=ShiroKit.getLoginUser();
			if(simpleUser==null) {
				renderError("会话过期，退出重新登录！！！");
				return;
			}
			
			String path = "/upload/csv" + "/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			
			BizKml bizKml = new BizKml();
			bizKml.setId(UuidUtil.getUUID());
			bizKml.setName(uploadFile.getFileName());
			bizKml.setSceneId(sceneId);
			bizKml.setStatus("0");
			bizKml.setSceneName(bizScene.getTitle());
			bizKml.setPath(path);
			bizKml.setCreateUserId(simpleUser.getId());
			bizKml.setCreateUserName(simpleUser.getName());
			if(uploadFile.getFile().renameTo(file) && bizKml.save()) {
				renderSuccess("导入成功，已启动异步入库进程！");
			    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
			        @Override
			        public Integer get() {
			            try {
			            	bizKml.setStatus("1");
			            	bizKml.setRemark("开始入库:"+DateKit.toStr(new Date(System.currentTimeMillis()),"yyyy-mm-dd hh:mm:ss" ));
			            	bizKml.update();
			            	
			        		Workbook workbook=ExcelUtil.readExcel(rootPath+path);
			        		List<Sheet> sheets= ExcelUtil.getSheet( workbook);
			        		if(sheets!=null && sheets.size()>0) {
			        			for(Sheet sheet:sheets) {
			        				List<Row> rows=ExcelUtil.getRows(sheet);
			        				for(int i=1;i<rows.size()-1;i++) {
			        					List<Cell> cells=ExcelUtil.getCells(rows.get(i));
			        					String classify=cells.get(5).getStringCellValue();
			        					String[] classifys=classify.split(";");
			        					String  LayerId="root";
			        					BizLayer parentBizLayer = null;
			        					String parentId="root";
			        					for(int j=0;j<classifys.length;j++) {
				        					BizLayer bizLayer=BizLayer.dao.findFirst("SELECT * FROM "+BizLayer.TABLE_NAME+" WHERE code=? AND sceneId=? ",classifys[j],sceneId);
				        					if(parentBizLayer!=null) {
				        						parentId=parentBizLayer.getId();
				        					}else {
				        						parentId="root";
				        					}
				        					
				        					if(bizLayer==null) {
				        						bizLayer=new BizLayer();
				        						bizLayer.setId(UuidUtil.getUUID());
				        						bizLayer.setSceneId(sceneId);
				        						bizLayer.setCode(classifys[j]);
				        						bizLayer.setName(classifys[j]);
				        						bizLayer.setParentId(parentId);
				        						bizLayer.setType("folder");
				        						bizLayer.save();
				        					}
				        					parentBizLayer=bizLayer;
			        					}
			        					if(parentBizLayer!=null) {
			        						LayerId=parentBizLayer.getId();
			        					}
			        					String name=cells.get(0).getStringCellValue();
			        					double Longitude=cells.get(1).getNumericCellValue();
			        					double Latitude=cells.get(2).getNumericCellValue();
			        					String description="";
			        					try {
			        						description=cells.get(3).getStringCellValue();
			        					}catch (Exception e) {
										}
			        					String phone="";
			        					try {
			        						phone=cells.get(4).getStringCellValue();
			        					}catch (Exception e) {
										}
			        					
			        					
			        					Point bizPoint=Point.dao.findFirst("SELECT * FROM "+Point.TABLE_NAME+" WHERE x=? AND  y=?   AND name=? AND sceneId=? ",
			        							Longitude,Latitude,name,sceneId);
			        					if(bizPoint==null) {
			        						bizPoint=new Point();
			        						bizPoint.setId(UuidUtil.getUUID());
			        						bizPoint.setName(name);
			        						bizPoint.setX(Longitude);
			        						bizPoint.setY(Latitude);
			        						bizPoint.setZ(0.0);
			        						bizPoint.setLayerId(LayerId);
			        						bizPoint.save();
			        						
			        						if(StrKit.notBlank(phone)) {
			        							BizProperty bizProperty=new BizProperty();
			        							bizProperty.setId(UuidUtil.getUUID());
			        							bizProperty.setKey(rows.get(0).getCell(4).getStringCellValue());
			        							bizProperty.setValue(phone);
			        							bizProperty.setObjId(bizPoint.getId());
			        							bizProperty.setEvent("MOUSE_HOVER");
			        							bizProperty.setSort(1);
			        							bizProperty.save();
			        						}
			        						
			        						if(StrKit.notBlank(description)) {
			        							BizProperty bizProperty=new BizProperty();
			        							bizProperty.setId(UuidUtil.getUUID());
			        							bizProperty.setKey(rows.get(0).getCell(3).getStringCellValue());
			        							bizProperty.setValue(description);
			        							bizProperty.setObjId(bizPoint.getId());
			        							bizProperty.setEvent("MOUSE_HOVER");
			        							bizProperty.setSort(2);
			        							bizProperty.save();
			        						}

			        						BizLayer bizLayerForPoint=new BizLayer();
			        						bizLayerForPoint.setId(bizPoint.getId());
			        						bizLayerForPoint.setName(bizPoint.getName());
			        						bizLayerForPoint.setParentId(LayerId);
			        						bizLayerForPoint.setType("point");
			        						bizLayerForPoint.setDataId(bizPoint.getId());
			        						bizLayerForPoint.save();
			        					}
			        				}
			        			}
			        		}
			            	bizKml.setStatus("2");
			            	bizKml.setRemark(bizKml.getRemark()+"--->入库完成:"+DateKit.toStr(new Date(System.currentTimeMillis()),"yyyy-mm-dd hh:mm:ss" ));
			            	bizKml.update();
			            } catch (Exception e) {
			                e.printStackTrace();
			                bizKml.setStatus("3");
			                bizKml.setRemark(e.getMessage());
			                bizKml.update();
			            }
			            return 3;
			        }
			    }, executor);
			    future.thenAccept(e -> System.out.println(e));
			}else {
				renderError("导入失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}

}
